/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.*;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author Fabian
 */
//TreeDropTarget.java
//A quick DropTarget that's looking for drops from draggable JTrees.
//
public class TreeDropTarget implements DropTargetListener {

    DropTarget target;
    JTree targetTree;

    /**
     * 
     * @param tree
     */
    public TreeDropTarget(JTree tree) {
        targetTree = tree;
        target = new DropTarget(targetTree, this);
    }

    /*
     * Drop Event Handlers
     */
    private TreeNode getNodeForEvent(DropTargetDragEvent dtde) {
        Point p = dtde.getLocation();
        DropTargetContext dtc = dtde.getDropTargetContext();
        JTree tree = (JTree) dtc.getComponent();
        TreePath path = tree.getClosestPathForLocation(p.x, p.y);
        return (TreeNode) path.getLastPathComponent();
    }

    @Override
    public void dragEnter(DropTargetDragEvent dtde) {
        TreeNode node = getNodeForEvent(dtde);
        if (node.isLeaf()) {
            dtde.rejectDrag();
        } else {
            // start by supporting move operations
            //dtde.acceptDrag(DnDConstants.ACTION_MOVE);
            dtde.acceptDrag(dtde.getDropAction());
        }
    }

    public void dragOver(DropTargetDragEvent dtde) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) getNodeForEvent(dtde);
        
        if (node.getLevel() != 2) {
            //System.out.println("Copia rechazada");
            dtde.rejectDrag();
        } else {
            // start by supporting move operations
            //dtde.acceptDrag(DnDConstants.ACTION_MOVE);
            dtde.acceptDrag(dtde.getDropAction());
        }
    }

    public void dragExit(DropTargetEvent dte) {
    }

    public void dropActionChanged(DropTargetDragEvent dtde) {
    }

    public void drop(DropTargetDropEvent dtde) {
        Point pt = dtde.getLocation();
        DropTargetContext dtc = dtde.getDropTargetContext();
        JTree tree = (JTree) dtc.getComponent();
        TreePath parentpath = tree.getClosestPathForLocation(pt.x, pt.y);
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode) parentpath.getLastPathComponent();
        DefaultTreeModel model1 = (DefaultTreeModel) tree.getModel();
        if (parent.isLeaf()) {
            Transferable tr = dtde.getTransferable();
            DataFlavor[] flavors = tr.getTransferDataFlavors();
            dtde.acceptDrop(dtde.getDropAction());
            TreePath p = null;
            try {
                p = (TreePath) tr.getTransferData(flavors[0]);
            } catch (UnsupportedFlavorException ex) {
                Logger.getLogger(TreeDropTarget.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(TreeDropTarget.class.getName()).log(Level.SEVERE, null, ex);
            }
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) p.getLastPathComponent();
            DefaultMutableTreeNode nodeFinal = new DefaultMutableTreeNode(node.getParent().toString() +"."+node.toString());
//            model1.insertNodeInto(node, parent, 0);
            if(node.getChildCount()>0){
                return;
            }
            model1.insertNodeInto(nodeFinal, parent, 0);
            dtde.dropComplete(true);
            return;
        }

        try {
            Transferable tr = dtde.getTransferable();
            DataFlavor[] flavors = tr.getTransferDataFlavors();
            for (int i = 0; i < flavors.length; i++) {
                if (tr.isDataFlavorSupported(flavors[i])) {
                    dtde.acceptDrop(dtde.getDropAction());
                    TreePath p = (TreePath) tr.getTransferData(flavors[i]);
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) p.getLastPathComponent();
                    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
                    for (int j = 0; j < parent.getLeafCount(); j++) {
                        
                        if (parent.getChildAt(j).toString().equals(node.toString())) {
                          
                            //dtde.rejectDrop();
                            dtde.dropComplete(true);
                            return;
                        }
                    }
                    model.insertNodeInto(node, parent, 0);
                    dtde.dropComplete(true);
                    return;
                }
            }
            dtde.rejectDrop();
        } catch (UnsupportedFlavorException e) {
            e.printStackTrace();
           
            dtde.rejectDrop();
        } catch (IOException e) {
            e.printStackTrace();
            dtde.rejectDrop();
        }
    }
}